var time = require('../../utils/util.js');
Page({
  data: {
    formats: {},
    bottom: 0,
    readOnly: false,
    placeholder: '开始输入...',
    _focus: false,
    array: ['美国', '中国', '巴西', '日本'],
    objectArray: [{
      id: 0,
      name: '美国'
    },
    {
      id: 1,
      name: '中国'
    },
    {
      id: 2,
      name: '巴西'
    },
    {
      id: 3,
      name: '日本'
    }
    ],
    index: 0,
  },

  onLoad() {

  },
  formSubmit(e) {
    this.editorCtx.getContents({
      success(res) {
        console.log('内容:', res.html)
        console.log('标题:', e.detail.value.title)
      }
    })
  },
  bindPickerChange(e) {
    // 选择了课程类别
    console.log(e.detail.value)
    this.setData({
      index: e.detail.value
    })

  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },

  undo() {
    this.editorCtx.undo()
  },
  redo() {
    this.editorCtx.redo()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat(e) {
    console.log(e)
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {

    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        //把图片上传到云空间
        wx.showLoading({
          title: '正在上传图片',
        })
        wx.cloud.uploadFile({
          cloudPath: `news/upload/${time.formatTime(new Date)}/${Math.floor(Math.random() * 100000000)}.png`, // 上传至云端的路径
          filePath: res.tempFilePaths[0], // 临时文件路径
          success: cover => {
            //上传成功了,把他返回到编辑器

            that.editorCtx.insertImage({
              src: cover.fileID,
              data: {
                id: cover.fileID,
                role: 'god'
              },
              success: function () {
                wx.hideLoading()
              }
            })
            //插入编辑器结束

          }
        })
        //云文件上传结束

      }
    })
    //选择图片结束
  }
})